
package Type_1_arr.title7_P44;


import java.util.Scanner;

//44. 开发商购买土地(卡码网)
public class P44BuyLand {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入行数n:");
        int n = scanner.nextInt();
        System.out.println("请输入列数m:");
        int m = scanner.nextInt();


        int[][] grid = new int[n][m];  //TODO 权重矩阵
        int totalSum = 0;             //TODO  总权重

        // 输入数据并计算总和
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.printf("请输入第%d行,第%d块地的权值：", i + 1, j + 1);
                grid[i][j] = scanner.nextInt();
                totalSum += grid[i][j];   //求和
            }
        }

        int minDiff = Integer.MAX_VALUE;  //TODO 返回的结果
        int currentSum = 0;               //TODO  用户汇总计算

        // 按行分割：计算前i行的和
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                currentSum += grid[i][j];  //TODO 计算行累计
            }
            int diff = Math.abs(currentSum - (totalSum - currentSum));
            minDiff = Math.min(minDiff, diff);
        }

        currentSum = 0; // 重置

        // 按列分割：计算前j列的和
        for (int j = 0; j < m; j++) {
            for (int i = 0; i < n; i++) {
                currentSum += grid[i][j];  //TODO 计算列累计
            }
            int diff = Math.abs(currentSum - (totalSum - currentSum));
            minDiff = Math.min(minDiff, diff);
        }

        System.out.println(minDiff);
        scanner.close();
    }

}